package com.ccnu.sm.jdbc;/*
 * @author raohj
 * @date 2019/11/1016:13
 * @description add your comment
 */

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/*
* 功能描述 参数绑定的测试
* @author raohj
* @date 2019/11/11
*/

@Service
public class RNamedParameterJdbcTemplate {
    private static final Log log = LogFactory.getLog(RNamedParameterJdbcTemplate.class);
    @Autowired
    private DataSource dataSource;
    public int test(){
        NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);

        log.info("测试namedParameterJdbcTemplate进行参数绑定的查询测试");
        String sqlExe = "select * from t_cust where cust_no=:cust_no";
        Map<String, Object> paramMap = new HashMap<>();

        // 参数通过Map存放
        paramMap.put("cust_no", "20191104");
        SqlParameterSource sqlParameterSource  = new MapSqlParameterSource(paramMap);
        RCust rcust = namedParameterJdbcTemplate.queryForObject(sqlExe, sqlParameterSource, new RCustMapper());
        log.info("使用Map作为参数，查询结果:" + rcust.toString());

        // 参数通过Pojo传递
        RCust custCon = new RCust();
        custCon.setCustNo("20191104");
        sqlParameterSource = new BeanPropertySqlParameterSource(custCon);
        sqlExe = "select * from t_cust where cust_no=:custNo";
        rcust = namedParameterJdbcTemplate.queryForObject(sqlExe, sqlParameterSource, new RCustMapper());
        log.info("使用POJO作为参数，查询结果:" + rcust.toString());

        return 1;
    }
}
